﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ProductManager
{
    public partial class ProviderDetail : Form
    {
        private string _providerID = "";
        public string ProviderID
        {
            get { return _providerID; }
            set { _providerID = value; }
        }

        public ProviderDetail()
        {
            InitializeComponent();
        }

        public void RefreshCategory()
        {
            DataTable categories = DBAccess.GetProviderCategory(_providerID);
            if (categories != null)
            {
                lvCategory.Items.Clear();
                foreach (DataRow row in categories.Rows)
                {
                    lvCategory.Items.Add(new ListViewItem(new string[] {
                        row["Name"].ToString(), row["ID"].ToString() }));
                }
            }
        }

        public void RefreshProduct()
        {
            DataTable products = DBAccess.GetProviderProduct(_providerID);
            if (products != null)
            {
                lvProduct.Items.Clear();
                foreach (DataRow row in products.Rows)
                {
                    lvProduct.Items.Add(new ListViewItem(new string[] {
                        row["Name"].ToString(), row["Price"].ToString() }));
                }
            }
        }

        public void AddExistCategory(string id)
        {
            DBAccess.AddProviderCategory(_providerID, id);
            RefreshCategory();
        }

        private void ProviderDetail_Load(object sender, EventArgs e)
        {
            RefreshCategory();
            RefreshProduct();
        }

        private void btnAddCategory_Click(object sender, EventArgs e)
        {
            AddCategory frmNew = new AddCategory();
            frmNew.OwnerType = 1;
            frmNew.ShowDialog(this);
        }

        private void btnDeleteCategory_Click(object sender, EventArgs e)
        {
            if (lvCategory.SelectedItems.Count == 1)
            {
                if (DBAccess.DeleteProviderCategory(_providerID, lvCategory.SelectedItems[0].SubItems[1].Text))
                {
                    RefreshCategory();
                }
                else
                {
                    MessageBox.Show("Delete category failed!!!");
                }
            }
            else
            {
                MessageBox.Show("Please choose one category!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
